package com.gmail.avereshchaga.cashierdeskconnectengine;

import com.gmail.avereshchaga.cashierdeskconnect.CashierDeskConnect;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
    dtd = "-//com.gmail.avereshchaga.cashierdeskconnectengine//Connect//EN",
autostore = false)
@TopComponent.Description(
    preferredID = "ConnectTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "com.gmail.avereshchaga.cashierdeskconnectengine.ConnectTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
    displayName = "#CTL_ConnectAction",
preferredID = "ConnectTopComponent")
@Messages({
    "CTL_ConnectAction=Connect",
    "CTL_ConnectTopComponent=Connect Window",
    "HINT_ConnectTopComponent=This is a Connect window"
})
public final class ConnectTopComponent extends TopComponent {

    public ConnectTopComponent() {
        initComponents();
        setName(Bundle.CTL_ConnectTopComponent());
        setToolTipText(Bundle.HINT_ConnectTopComponent());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        hostField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();
        connectButton = new javax.swing.JButton();
        closeSessionButton = new javax.swing.JButton();
        closeSessionButton.setEnabled(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.jLabel1.text")); // NOI18N

        hostField.setText(org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.hostField.text")); // NOI18N
        hostField.setInputVerifier(new com.gmail.avereshchaga.validation.FieldVerifier());

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.jLabel2.text")); // NOI18N

        usernameField.setText(org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.usernameField.text")); // NOI18N
        usernameField.setInputVerifier(new com.gmail.avereshchaga.validation.AlphanumericUsernameVerifier());

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.jLabel3.text")); // NOI18N

        passwordField.setText(org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.passwordField.text")); // NOI18N
        passwordField.setInputVerifier(new com.gmail.avereshchaga.validation.FieldVerifier());
        passwordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(connectButton, org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.connectButton.text")); // NOI18N
        connectButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                connectButtonMouseEntered(evt);
            }
        });
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(closeSessionButton, org.openide.util.NbBundle.getMessage(ConnectTopComponent.class, "ConnectTopComponent.closeSessionButton.text")); // NOI18N
        closeSessionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeSessionButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(30, 30, 30)
                        .addComponent(hostField))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
                                    .addComponent(usernameField))
                                .addGap(0, 104, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(connectButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(closeSessionButton)))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {closeSessionButton, connectButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connectButton)
                    .addComponent(closeSessionButton))
                .addContainerGap(24, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
    }//GEN-LAST:event_passwordFieldActionPerformed

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        String host = hostField.getText().trim();
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String connectionInfo = null;
        try {
            for (CashierDeskConnect cashierDeskConnect : Lookup.getDefault().lookupAll(CashierDeskConnect.class)) {
                connectionInfo = cashierDeskConnect.callServer(host, username, password);
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Connection error: " + ex, "Connection", 0);
        }
        if (connectionInfo.equals("Success Connection")) {
            JOptionPane.showMessageDialog(null, connectionInfo, "Connection", 1);
            hostField.setEnabled(false);
            usernameField.setEnabled(false);
            passwordField.setEnabled(false);
            closeSessionButton.setEnabled(true);
        } else {
            JOptionPane.showMessageDialog(null, "Wrong login or password", "Connection", 0);
        }
    }//GEN-LAST:event_connectButtonActionPerformed

    private void connectButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_connectButtonMouseEntered
        hostField.requestFocusInWindow();
    }//GEN-LAST:event_connectButtonMouseEntered

    private void closeSessionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeSessionButtonActionPerformed
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        try {
            for (CashierDeskConnect cashierDeskConnect : Lookup.getDefault().lookupAll(CashierDeskConnect.class)) {
                cashierDeskConnect.closeSession(username, password);
                cashierDeskConnect.setHost(null);
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        usernameField.setText("");
        passwordField.setText("");
        hostField.setEnabled(true);
        usernameField.setEnabled(true);
        passwordField.setEnabled(true);
        closeSessionButton.setEnabled(false);
    }//GEN-LAST:event_closeSessionButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeSessionButton;
    private javax.swing.JButton connectButton;
    private javax.swing.JTextField hostField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField usernameField;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
}
